<template>
  <div class="w100 h100  page-padding-bg" style="box-sizing: border-box;position: relative;">
    <div class="week">
      <!-- 日牌评吸  -->
      <div class="week_title">
        <!-- <div> 
          <span>任务名称：</span><lay-input size="sm" placeholder="请输入" @keydown.enter="search_tab" v-model="search1"></lay-input>
        </div> -->
        <div> <span>任务时间：</span>

          <!-- <lay-input size="sm" placeholder="请输入" @keydown.enter="search_tab" v-model="search2"></lay-input> -->
          <!-- <lay-date-picker simple type="date" size="sm" placeholder="请选择" v-model="search2" @change="search_tab"></lay-date-picker> -->
          <el-date-picker  :disabled-date="undefined" class="data_time" v-model="search2" type="daterange" range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" :size="''" value-format="YYYY-MM-DD" @change="search_tab" />
        </div>

        <div>
          <lay-button class="btn-search" size="sm" type="normal" @click="search_tab"> 查询</lay-button>
          <lay-button class="btn-resert" size="sm" @click="resert">重置</lay-button>
          <!-- <lay-button class="btn-resert" size="sm" @click="export_table_all"> 导出 </lay-button> -->
        </div>
      </div>
      <div class="week_table">
        <lay-table :resize="true" :height="'100%'" :columns="columns" :data-source="dataSource">
          <template v-slot:operator="{ row }">
            <lay-button class="btn-view" size="xs" type="" v-permissions="'taskWeek_view'" v-if="row.status=='1'" @click="smoke_view(row)">查看</lay-button>
            <lay-button size="xs" type="primary" @click="smoke_test(row)" v-permissions="'taskWeek_view'" v-if="row.status!='1'">评吸</lay-button>
            <!-- <lay-button size="xs" @click="export_table(row)" v-if="nowMenuBtnArr.includes('导出')&&row.status=='1'"> 导出 </lay-button> -->
          </template>
          <template #state="{ row }">
            <lay-switch v-model="row.switch_state" onswitch-text="开启" unswitch-text="关闭"></lay-switch>
          </template>

        </lay-table>
        <Pagination :currentPage="currentPage" :limit="limit" :total="total" @page_change="page_change"></Pagination>
      </div>

    </div>

    <!-- 弹层 -->
    <!-- <lay-layer :teleportDisabled="true" v-model="dialogVisible" :area="['100%', '100%']" :title="''"  class="dialog-page">
      <div class="dialog-page-content">
        <h1>周评吸</h1>
        <hr />
        <div class="top">
          <div> <span>评吸时间：</span><lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.meetingTime"></lay-input></div>
          <div> <span>评吸任务：</span><lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.taskName"></lay-input></div>
          <div> <span>评吸烟支：</span><lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.allowanceName"></lay-input></div>
          <div> <span>评吸重量：</span><lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.smokeWeight"></lay-input></div>
        </div>
        <div class="content">
          <div style="padding-bottom: 15px;box-sizing: border-box;">
            <div class="top-header df-c">评吸明细</div>
            <hr />
            <div class="table-group">
              <table border>
                <thead>
                  <tr>
                    <th>评吸人员</th>
                    <th>评吸结论</th>
                    <th>综合判定</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td class="pl10">{{ system.description }}</td>
                    <td> <lay-input v-model="p_qualityDescription" placeholder="请输入" size="sm"></lay-input></td>
                    <td>
                      <lay-select v-model="p_determine" placeholder="请选择" style="width: 100%;" size="sm">
                        <lay-select-option value="0" label="正常"></lay-select-option>
                        <lay-select-option value="1" label="不正常"></lay-select-option>
                        <lay-select-option value="2" label="基本正常"></lay-select-option>
                      </lay-select>
                    </td>
                  </tr>
                </tbody>
              </table>

            </div>
          </div>
        </div>
      </div>
    </lay-layer> -->

    <el-dialog :append-to-body="false" ref="myDialog" v-model="dialogVisible" width="100%" class="dialog-page" style="margin-top: 0;">
      <div class="dialog-page-content">
        <h1>周评吸</h1>
        <hr />
        <div class="top">
          <div> <span>评吸时间：</span> {{ detailInfo[0]?.meetingTime|| '-' }}
            <!-- <lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.meetingTime"></lay-input> -->
          </div>
          <div> <span>评吸任务：</span>{{ detailInfo[0]?.taskName|| '-' }}
            <!-- <lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.taskName"></lay-input> -->
          </div>
          <!-- <div> <span>生产日期：</span>{{detailInfo[0]?.productionDate|| '-'}} -->
            <!-- <lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.allowanceName"></lay-input> -->
          <!-- </div> -->
          <!-- <div> <span>烟支重量：</span>{{detailInfo[0]?.smokeWeight|| '-'}}g -->
            <!-- <lay-input size="sm" placeholder="请输入" disabled v-model="detailInfo.smokeWeight"></lay-input> -->
          <!-- </div> -->
        </div>
        <div class="content">
          <div style="padding-bottom: 15px;box-sizing: border-box;">
            <div class="top-header df-c">评吸明细</div>
            <hr />
            <div class="table-group">
              <table border>
                <thead>
                  <tr>
                    <th>评吸人员</th>
                    <th>牌号（规格）</th>
                    <th>烟支重量/g</th>
                    <th>生产日期</th>
                    <th>评吸结论</th>
                    <!-- <th>综合判定</th> -->
                  </tr>
                </thead>
                <!-- <tbody>
                  <template>
                    <tr v-for="(item, index) in detailInfo" :key="index">
                      <td class="pl10">{{ system.description }}</td>
                      <td class="pl10">{{ item.smokeName }}</td>
                      <td> <lay-input v-model="item.conclusion" placeholder="请输入" :disabled="isView"></lay-input></td>
                      <td>
                        <lay-select v-model="item.determine" placeholder="请选择" style="width: 100%;" :disabled="isView">
                          <lay-select-option value="0" label="正常"></lay-select-option>
                          <lay-select-option value="1" label="不正常"></lay-select-option>
                          <lay-select-option value="2" label="基本正常"></lay-select-option>
                        </lay-select>
                      </td> 
                    </tr>
                  </template>
                </tbody> -->

                <tbody>
                  <tr v-for="(item, index) in detailInfo" :key="index">
                    <td class="pl10">{{ system.description }}</td>
                    <td class="pl10">{{ item.smokeName }}</td>
                    <td class="pl10">{{ item.smokeWeight }}</td>
                    <td class="pl10">{{ item.productionDate }}</td>
                    
                    <td> <lay-input v-model="item.conclusion" placeholder="请输入" :disabled="isView"></lay-input></td>
                    <!-- <td>
                      <lay-select v-model="item.determine" placeholder="请选择" style="width: 100%;" :disabled="isView">
                        <lay-select-option value="0" label="正常"></lay-select-option>
                        <lay-select-option value="1" label="不正常"></lay-select-option>
                        <lay-select-option value="2" label="基本正常"></lay-select-option>
                      </lay-select>
                    </td> -->
                  </tr>
                </tbody>
              </table>

            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">

          <!-- <lay-button type="primary" @click="enter(1)" v-if="!isView || isEnter"> 保存 </lay-button> -->
          <lay-button type="primary" @click="enter(2)" v-if="!isView || isEnter"> 确认 </lay-button>
          <lay-button class="layui-btn layui-bg-blue" @click="dialogVisible = false">关闭</lay-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>
  
  <script setup lang="ts">
import http from "@/http/index";
import { layer } from "@layui/layui-vue";
import { onMounted, ref } from "vue";
import { useCounterStore } from "@/current";
import { storeToRefs } from "pinia"; // cnpm i pinia --save  2.1.3
import { time_YY_DD_MM_HH_MI_SS } from "@/tools/time";
import Pagination from "@/components/pagination.vue";

const store = useCounterStore();
const { system, nowMenuBtnArr ,isShowUserCenterRef} = storeToRefs(store); //  数据
const {get_user_list}  = store
onMounted(() => {
  get_list(pageNo.value, pageSize.value);
});

// 禁止选择的逻辑
const disabledDate = (time) => {
  let flag = false;
  try {
    // 获取当前日期
    const now = new Date();
    // 清除小时等信息，以便只比较年月日
    now.setHours(0, 0, 0, 0);

    // 清除参数时间的日以下的部分
    const incomingDate = new Date(time);
    incomingDate.setHours(0, 0, 0, 0);

    flag = incomingDate > now;
  } catch (err) {
    console.log(err);
  }

  // 如果参数时间大于等于当前时间，则禁止选择
  return flag;
};
// 表格配置
const columns = ref([
  // {
  //   title: "任务ID",
  //   key: "taskId",
  // },
  {
    title: "任务名称",
    key: "taskName",
  },
  // {
  //   title: "评吸结论",
  //   key: "",
  // },
  // {
  //   title: "综合判定",
  //   key: "",
  // },
  {
    title: "评吸时间",
    key: "meetingTime",
  },
  {
    title: "操作",
    customSlot: "operator",
    key: "operator",
  },
]);
const dataSource = ref([]);

const search1 = ref("");
const search2 = ref("");
// 分页
const limit = ref(10);
const total = ref(0);
const currentPage = ref(1);
const pageNo = ref(1);
const pageSize = ref(10);

// 分页事件
const page_change = async (page, limt) => {
  console.log(page, limt);
  currentPage.value = page;
  pageNo.value = page;

  await get_list(page, limt);
};

// daochu1
const export_table = async (row) => {
  //  let userId = system.value.id

  console.log(row);

  const res = await http.corsApi(`/taskDetail/exportWeekFile/${row.taskId}`, "get", {}, { is_msg: false, formData: true });

  // console.log(res);

  if (res.data) {
    // res 为后端返回的响应对象
    // let blob = new Blob([res]);
    let url = window.URL.createObjectURL(res.data);
    let a = document.createElement("a");
    a.href = url;
    a.download = decodeURI(res.headers["content-disposition"]).split("filename=")[1].replace(/"/g, "") || new Date().getTime() + ".zip";
    a.click();
    window.URL.revokeObjectURL(url);
    layer.msg("导出成功", { icon: 1, time: 2000 });
  }
};

/**全部导出 */
async function export_table_all() {

  let params = {
    taskName: search1.value,
    // 任务类型 0:日评吸 1:周评吸
    type: 1,
    beginTime: search2?.value[0] || "",
    endTime: search2?.value[1] || "",
  }

  console.log("导出全部", params)

  const res = await http.corsApi(`/taskDetail/exportWeekAll`, "get", params, { is_msg: false, formData: true });


  if (res.data) {
    // res 为后端返回的响应对象
    // let blob = new Blob([res]);
    let url = window.URL.createObjectURL(res.data);
    let a = document.createElement("a");
    a.href = url;
    a.download = decodeURI(res.headers["content-disposition"]).split("filename=")[1].replace(/"/g, "") || new Date().getTime() + ".zip";
    a.click();
    window.URL.revokeObjectURL(url);
    layer.msg("导出成功", { icon: 1, time: 2000 });
  }
}

// 页面初始化数据
const detailInfo = ref([]);

// 控制弹层、
const dialogVisible = ref(false);
// 表格绑定
const p_qualityDescription = ref("");
const p_determine = ref("");

// 保存1 发布2
const enter = async (flag) => {
  let method = "post";

  if (detailInfo.value && detailInfo.value.length > 0) {
    method = "put";
  }

  let data: any = {
    type: "1",
    status: "",
    taskId: weekid.value,
    taskDetailReqList: [],
  };
  if (flag === 1) {
    data.status = "0";
  } else if (flag === 2) {
    data.status = "1";
  }

  detailInfo.value.forEach((element) => {
    data.taskDetailReqList.push(element);
  });

  let isFull = true;
  data.taskDetailReqList.forEach((item) => {
    // determine
    // if (!item.conclusion || !item.determine) {
    if (!item.conclusion ) {
      isFull = false;
    }
  });
  if (!isFull) {
    layer.msg(`请检查填写是否完整`, { icon: 2, time: 1500 });
    return false;
  }
  console.log(data);

  const res = await http.corsApi(`/taskDetail/submit`, method, data);
  console.log(res);

  if (res.data) {
    layer.confirm(flag == 1 ? "保存成功" : "发布成功", { icon: 1 });
    await get_list(pageNo.value, pageSize.value);
    await get_detail(weekid.value);
    dialogVisible.value = false;
  }
};

const weekid = ref("");
// 评吸
const smoke_test = async (row) => {
  isView.value = false;
  // dialogVisible.value = true;
  weekid.value = row.id;
  await get_detail(row.taskId);
};
const isView = ref(true);
const isEnter = ref(false);
// 查看
const smoke_view = async (row) => {
  isView.value = true;
  // dialogVisible.value = true;
  weekid.value = row.id;
  await get_detail(row.taskId);
};

const get_detail = async (id) => {
  const res = await http.corsApi(`/taskDetail?taskId=${id}`, "get", {},{is_msg:false});

  console.log(res);
  // res.data.allowanceList
  if(res.data){
    dialogVisible.value = true;
    detailInfo.value = res.data;
  }else{
    layer.msg('检测到您还未签名，请先签名',{time:2500})
    await get_user_list()
    isShowUserCenterRef.value.open();
  }

  // if (res.data.taskWeekDetailRepList && res.data.taskWeekDetailRepList.length > 0) {
  //   // isAddEdit.value = "edit";
  //   p_qualityDescription.value = res.data.taskWeekDetailRepList[0].conclusion;
  //   p_determine.value = res.data.taskWeekDetailRepList[0].determine;
  // } else {
  //   // isAddEdit.value = "add";
  //   p_qualityDescription.value = "";
  //   p_determine.value = "";
  // }
};

const search_tab = async () => {
  await get_list(pageNo.value, pageSize.value);
};

const get_list = async (page: number | string, pagesize: number | string) => {
  const res = await http.corsApi("/taskDetail/exportQuery", "get", {
    pageNo: page,
    pageSize: pagesize,
    taskName: search1.value,
    // meetingTime: search2.value,
    // 任务类型 0:日评吸 1:周评吸
    type: 1,
    beginTime: search2?.value[0] || "",
    endTime: search2?.value[1] || "",
  });

  console.log(res);
  dataSource.value = res.data.list;
  total.value = res.data.totalCount;
  isEnter.value = res.data.list[0]?.status == "2";
};

// 重置
const resert = async () => {
  search1.value = "";
  search2.value = "";
  await get_list(pageNo.value, pageSize.value);
};
</script>
  
  <style scoped lang="scss">
.week {
  width: 100%;
  // height: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;

  position: relative;
  &_title {
    display: flex;
    justify-content: space-between;
    > div {
      display: flex;
      align-items: center;
      margin-right: 35px;
      span {
        width: 70px;
        text-align: right;
      }
      .layui-input {
        width: 300px;
      }
    }
  }

  &_btn {
    // margin-right: 8px;
    margin-top: 20px;
  }
  &_table {
    margin-top: 20px;
  }
}

:deep(.el-dialog),
.layui-layer {
  width: 100%;
  height: calc(100% - 0px);
  height: 100%;
  margin: 0;
  .dialog-page-content {
    width: 100%;
    height: 100%;
    h1 {
      text-align: center;
      color: #000;
      font-size: 24px;
    }
    .top {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      margin: 20px 0 50px 0;
      padding: 0 20px;
      box-sizing: border-box;
      > div {
        width: 40%;
        display: flex;
        align-items: center;
        margin-right: 15px;
        margin-bottom: 15px;
        span {
          width: 100px;
          text-align: right;
        }
      }
    }
    .content {
      padding: 0 20px;
      box-sizing: border-box;

      > div {
        box-shadow: 0 0 5px #ccc;
        // border: 1px solid #ccc;
        .top-header {
          padding: 8px 0;
          box-sizing: border-box;
          text-align: center;
          width: 100%;
        }

        table {
          width: 100%;

          th {
            padding: 6px 8px;
          }
        }
      }

      .table-group {
        padding: 15px 15px 0 15px;
        box-sizing: border-box;
        width: 100%;
        // height: 500px;
        // overflow-y: scroll;
        box-sizing: border-box;
        // height: 150px;
      }
      ::-webkit-scrollbar {
        width: 4px;
        height: 4px;
        background-color: #e4e4e4;
        border-radius: 2px;
      }
      //滚动条的滑块
      ::-webkit-scrollbar-thumb {
        background-color: #b4b7c0;
        border-radius: 2px;
      }
    }
  }
}
.pl10 {
  padding-left: 10px;
}
:deep(.el-overlay-dialog) {
  position: absolute !important;
}
:deep(.el-overlay) {
  position: absolute !important;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
:deep(.el-date-editor){
  width: 200px;
}
</style>